package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import service.UserService;

import java.util.ArrayList;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService{
    @Reference
    private UserService userService;

    private Logger logger= LoggerFactory.getLogger(SpringSecurityUserService.class);
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取数据库的用户

        logger.error("111");
        logger.warn("222");
        logger.info("333");
        logger.debug("444");
        User user=userService.findByusername(username);
        //System.out.println(user);
        if(user == null){
            return null;
        }
        String password = user.getPassword();
        //2.进行授权
        ArrayList<GrantedAuthority> grantedAuthorityArrayList = new ArrayList();

        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            String roleKeyword = role.getKeyword();
            grantedAuthorityArrayList.add(new SimpleGrantedAuthority(roleKeyword));//加入角色
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                String keyword = permission.getKeyword();
                grantedAuthorityArrayList.add(new SimpleGrantedAuthority(keyword));  //加入权限
            }
        }

        //3.创建UserDetails对象返回
        org.springframework.security.core.userdetails.User userSecurity = new org.springframework.security.core.userdetails.User(username,password,grantedAuthorityArrayList);

        return userSecurity;
    }
}
